#!/bin/bash

test "${ACTION}" = "add" || exit 0
echo "${DEVNAME}" | grep -E "^/dev/input/event[0-9]+$" || exit 0

PARENTHASH=$(evsieve-helper parent "${DEVNAME}" input usb)
BASEFILE="/var/run/virtual-aimtrak-devices.${PARENTHASH}"
PIDFILE="${BASEFILE}.pid"
LOCKFILE="${BASEFILE}.lock"
LOGFILE="${BASEFILE}.log"

unlockAndExit() {
    rmdir "${LOCKFILE}"
    exit "${1}"
}

checkRunningPIDAndExit1() {
    test ! -e "${PIDFILE}" && return 0
    LPID=$(cat "${PIDFILE}")
    test ! -d "/proc/${LPID}" && return 0
    unlockAndExit 1
}

trylock() {
    # lock
    N=0
    while ! mkdir "${LOCKFILE}"
    do
	sleep 1
	let N++
	test "${N}" -gt 30 && exit 1 # give up
    done
}

trylock
checkRunningPIDAndExit1

CHILDREN=$(evsieve-helper children "${PARENTHASH}" input usb)
NDEVS=$(echo "${CHILDREN}" | wc -l)

    # Trigger                  : BTN_LEFT
    # L. side button           : BTN_TRIGGER
    # R. side button/offscreen : BTN_THUMB

if test "${NDEVS}" = 3
then
    DEV1=$(echo "${CHILDREN}" | head -1           | cut -f 1)
    DEV2=$(echo "${CHILDREN}" | head -2 | tail -1 | cut -f 1)
    DEV3=$(echo "${CHILDREN}" | head -3 | tail -1 | cut -f 1)

    nohup evsieve                                              \
            --input "${DEV1}" "${DEV2}" "${DEV3}" persist=exit \
            --map btn:trigger          btn:middle              \
            --map btn:thumb            btn:right               \
            --output name="Aimtrak ATRAK" >/dev/null 2>"${LOGFILE}" &
    echo $! > "${PIDFILE}"
else
    unlockAndExit 1
fi

unlockAndExit 0
